<template>
  <div class="role-list">
    <a-page-header
      title="角色管理"
      sub-title="管理系统中的角色，包括新增、编辑、删除和权限分配等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="角色名称">
          <a-input v-model:value="searchForm.name" placeholder="请输入角色名称" allowClear />
        </a-form-item>
        <a-form-item label="角色编码">
          <a-input v-model:value="searchForm.code" placeholder="请输入角色编码" allowClear />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="fetchRoleList">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="() => {
              searchForm.name = '';
              searchForm.code = '';
              fetchRoleList();
            }">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <a-button type="primary" @click="showAddModal" v-permission="'system:role:add'">
              <template #icon><plus-outlined /></template>新增角色
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="roleList" 
        :loading="tableLoading" 
        :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="showEditModal(record)" v-permission="'system:role:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-button type="primary" @click="showPermissionModal(record)" v-permission="'system:role:permission'">
                  <template #icon><key-outlined /></template>分配权限
                </a-button>
                <a-popconfirm
                title="确定要删除这个角色吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'system:role:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '正常' : '禁用' }}
            </a-tag>
            </template>
        </template>
    </a-table>

    <!-- 新增/编辑角色弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="角色名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item label="角色编码" name="code">
          <a-input v-model:value="formState.code" placeholder="请输入角色编码" :disabled="isEdit" />
        </a-form-item>
        <a-form-item label="角色描述" name="description">
          <a-textarea v-model:value="formState.description" placeholder="请输入角色描述" :rows="4" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status">
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分配权限弹窗 -->
    <a-modal
      title="分配权限"
      :visible="permissionModalVisible"
      @ok="handlePermissionModalOk"
      @cancel="handlePermissionModalCancel"
      :confirmLoading="permissionModalLoading"
      width="600px"
    >
      <div v-if="permissionModalVisible">
        <a-spin :spinning="permissionTreeLoading">
          <a-tree
            v-model:checkedKeys="checkedPermissionKeys"
            :treeData="permissionTree"
            checkable
            :defaultExpandAll="true"
            :fieldNames="{ key: 'key', title: 'title', children: 'children' }"
          >            
            <template #title="{ title, type }">
              <span>
                {{ title }}
                <a-tag v-if="type === 1" color="blue" size="small">菜单</a-tag>
                <a-tag v-else-if="type === 2" color="green" size="small">按钮</a-tag>
              </span>
            </template>
          </a-tree>
        </a-spin>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import { checkPermission, checkAndWarnPermission } from '@/utils/permission';

export default defineComponent({
  name: 'RoleList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    KeyOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const tableLoading = ref(false);
    const roleList = ref([]);
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });

    const searchForm = reactive({
      name: '',
      code: '',
    });

    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '角色编码',
        dataIndex: 'code',
        key: 'code',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '角色描述',
        dataIndex: 'description',
        key: 'description',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 280,
      },
    ];

    // 获取角色列表
    const fetchRoleList = () => {
      tableLoading.value = true;
      axios.get('/api/role/list', {
        params: {
          current: pagination.current,
          size: pagination.pageSize,
          name: searchForm.name || undefined,
          code: searchForm.code || undefined,
        },
      })
        .then(response => {
          if (response.data.code === 200) {
            roleList.value = response.data.data.records;
            pagination.total = response.data.data.total;
          } else {
            message.error(response.data.message || '获取角色列表失败');
          }
        })
        .catch(error => {
          console.error('获取角色列表失败:', error);
          message.error('获取角色列表失败');
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 表格分页、排序、筛选变化时触发
    const handleTableChange = (pag) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchRoleList();
    };

    // 删除角色
    const handleDelete = (id) => {
      axios.delete(`/api/role/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            message.success('删除成功');
            fetchRoleList();
          } else {
            message.error(response.data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除失败:', error);
          message.error('删除失败');
        });
    };

    // 新增/编辑角色相关
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const modalTitle = ref('新增角色');
    const isEdit = ref(false);
    const formRef = ref(null);
    const formState = reactive({
      name: '',
      code: '',
      description: '',
      status: 1,
    });

    const rules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { max: 50, message: '角色名称不能超过50个字符', trigger: 'blur' },
      ],
      code: [
        { required: true, message: '请输入角色编码', trigger: 'blur' },
        { max: 50, message: '角色编码不能超过50个字符', trigger: 'blur' },
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' },
      ],
    };

    // 显示新增角色弹窗
    const showAddModal = () => {
      isEdit.value = false;
      modalTitle.value = '新增角色';
      formState.name = '';
      formState.code = '';
      formState.description = '';
      formState.status = 1;
      modalVisible.value = true;
    };

    // 显示编辑角色弹窗
    const showEditModal = (record) => {
      isEdit.value = true;
      modalTitle.value = '编辑角色';
      formState.name = record.name;
      formState.code = record.code;
      formState.description = record.description;
      formState.status = record.status;
      formState.id = record.id;
      modalVisible.value = true;
    };

    // 处理弹窗确认
    const handleModalOk = () => {
      formRef.value.validate().then(() => {
        modalLoading.value = true;
        const apiUrl = isEdit.value ? `/api/role/${formState.id}` : '/api/role';
        const method = isEdit.value ? 'put' : 'post';
        
        axios[method](apiUrl, {
          name: formState.name,
          code: formState.code,
          description: formState.description,
          status: formState.status,
        })
          .then(response => {
            if (response.data.code === 200) {
              message.success(`${isEdit.value ? '编辑' : '新增'}成功`);
              modalVisible.value = false;
              fetchRoleList();
            } else {
              message.error(response.data.message || `${isEdit.value ? '编辑' : '新增'}失败`);
            }
          })
          .catch(error => {
            console.error(`${isEdit.value ? '编辑' : '新增'}失败:`, error);
            message.error(`${isEdit.value ? '编辑' : '新增'}失败`);
          })
          .finally(() => {
            modalLoading.value = false;
          });
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    // 处理弹窗取消
    const handleModalCancel = () => {
      modalVisible.value = false;
    };

    // 权限分配相关
    const permissionModalVisible = ref(false);
    const permissionModalLoading = ref(false);
    const permissionTreeLoading = ref(false);
    const permissionTree = ref([]);
    const checkedPermissionKeys = ref([]);
    const currentRoleId = ref('');

    // 获取权限树
    const fetchPermissionTree = () => {
      permissionTreeLoading.value = true;
      axios.get('/api/permission/tree')
        .then(response => {
          if (response.data.code === 200) {
            // 转换后端数据为树形组件所需格式
            permissionTree.value = convertToTreeData(response.data.data);
          } else {
            message.error(response.data.message || '获取权限树失败');
          }
        })
        .catch(error => {
          console.error('获取权限树失败:', error);
          message.error('获取权限树失败');
        })
        .finally(() => {
          permissionTreeLoading.value = false;
        });
    };
    
    // 将后端权限数据转换为树形组件所需格式
    const convertToTreeData = (data) => {
      return data.map(item => ({
        key: item.id,
        title: item.name,
        type: item.type,
        parentId: item.parentId,
        code: item.code,
        path: item.path,
        component: item.component,
        permission: item.permission,
        icon: item.icon,
        sort: item.sort,
        children: item.children ? convertToTreeData(item.children) : []
      }));
    };

    // 获取角色已分配的权限
    const fetchRolePermissions = (roleId) => {
      axios.get(`/api/role/${roleId}/permissions`)
        .then(response => {
          if (response.data.code === 200) {
            // 确保选中的权限键值与树形数据格式匹配
            checkedPermissionKeys.value = response.data.data;
          } else {
            message.error(response.data.message || '获取角色权限失败');
          }
        })
        .catch(error => {
          console.error('获取角色权限失败:', error);
          message.error('获取角色权限失败');
        });
    };

    // 显示分配权限弹窗
    const showPermissionModal = (record) => {
      currentRoleId.value = record.id;
      resetPermissionData();
      permissionModalVisible.value = true;
      
      // 先获取权限树，再获取角色已分配的权限
      fetchPermissionTree();
      fetchRolePermissions(record.id);
    };

    // 处理分配权限弹窗确认
    const handlePermissionModalOk = () => {
      permissionModalLoading.value = true;
      axios.post('/api/role/permission', {
        roleId: currentRoleId.value,
        permissionIds: checkedPermissionKeys.value,
      })
        .then(response => {
          if (response.data.code === 200) {
            message.success('权限分配成功');
            permissionModalVisible.value = false;
          } else {
            message.error(response.data.message || '权限分配失败');
          }
        })
        .catch(error => {
          console.error('权限分配失败:', error);
          message.error('权限分配失败');
        })
        .finally(() => {
          permissionModalLoading.value = false;
        });
    };
    
    // 重置权限树和选中的权限
    const resetPermissionData = () => {
      permissionTree.value = [];
      checkedPermissionKeys.value = [];
    };

    // 处理分配权限弹窗取消
    const handlePermissionModalCancel = () => {
      permissionModalVisible.value = false;
      resetPermissionData();
    };

    onMounted(() => {
      fetchRoleList();
    });

    return {
      tableLoading,
      roleList,
      pagination,
      searchForm,
      columns,
      fetchRoleList,
      handleTableChange,
      handleDelete,
      modalVisible,
      modalLoading,
      modalTitle,
      isEdit,
      formRef,
      formState,
      rules,
      showAddModal,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      permissionModalVisible,
      permissionModalLoading,
      permissionTreeLoading,
      permissionTree,
      checkedPermissionKeys,
      showPermissionModal,
      handlePermissionModalOk,
      handlePermissionModalCancel,
    };
  },
});
</script>

<style scoped>
.search-card {
  margin-bottom: 16px;
}
</style>